<template>
  <div id="app">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 头部区域 -->
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="9">
            <el-button type="primary" @click="addDialogVisible = true"
              >添加角色</el-button
            >
          </el-col>
        </el-row>
      </div>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!--在索引列前的展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 渲染一级权限菜单 -->
            <el-row
              v-for="(item, i) in scope.row.children"
              :key="item.id"
              :class="['bdbottom', 'Ycenter', i === 0 ? 'bdtop' : '']"
            >
              <el-col :span="5">
                <el-tag>{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限菜单 -->
              <el-col :span="19">
                <el-row
                  v-for="(item1, i1) in item.children"
                  :key="item1.id"
                  :class="['Ycenter', i1 === 0 ? '' : 'bdtop']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{ item1.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限菜单 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row.id, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 第一行利用type加上index做成了索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="Button(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="delRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-share"
              @click="setRightRoles(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closedRolesList"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addRolesList"
        :rules="addListRules"
        ref="addListRef"
        label-width="80px"
      >
        <el-form-item prop="roleName" label="角色名">
          <el-input v-model="addRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述">
          <el-input v-model="addRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editRoleList"
        :rules="editRoleRules"
        ref="editRoleRef"
        label-width="80px"
      >
        <el-form-item prop="roleName" label="角色名">
          <el-input v-model="editRoleList.roleName"></el-input>
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述">
          <el-input v-model="editRoleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesButton">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="getRightDialogClosed"
    >
      <el-tree
        :data="setRightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="dfkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色表单数据,roleId需要另外获取，将会放到计算属性中
      addRolesList: {
        roleName: '',
        roleDesc: ''
      },
      addListRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        roleDesc: [{ message: '请输入角色描述', trigger: 'blur' }]
      },
      // 控制编辑角色对话框的显示与隐藏
      editDialogVisible: false,
      //获取编辑角色的信息
      editRoleList: {},
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        roleDesc: [{ message: '请输入角色描述', trigger: 'blur' }]
      },
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限列表数据
      setRightList: [],
      treeProps: {
        children: 'children',
        // 树形控件的所有属性
        label: 'authName'
      },
      // 默认勾选的节点的 key 的数组
      dfkeys: [],
      //当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(res.data)
    },
    // 表单验证&添加角色
    addRoles() {
      this.$refs.addListRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', {
          roleName: this.addRolesList.roleName,
          roleDesc: this.addRolesList.roleDesc
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.addDialogVisible = false
        this.getRolesList()
        this.$message.success('添加角色成功')
      })
    },
    // 添加角色表单重置
    closedRolesList() {
      this.$refs.addListRef.resetFields()
    },
    //通过id获取编辑角色信息
    async Button(row) {
      const { data: res } = await this.$http.get('roles/' + row)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败')
      }
      this.editRoleList = res.data
      this.editDialogVisible = true
    },
    // 验证并提交表单
    editRolesButton() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleList.roleId,
          {
            roleName: this.editRoleList.roleName,
            roleDesc: this.editRoleList.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('更新角色失败')
        }
        this.$message.success('编辑角色成功')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 编辑表单重置
    editDialogClosed() {
      this.$refs.editRoleRef.resetFields()
    },
    // 删除角色
    async delRoles(row) {
      const delresult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (delresult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete('roles/' + row)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.getRolesList()
      this.$message.success('删除角色成功')
    },
    // 移除第三级角色指定权限
    async removeRightById(roleId, rightId) {
      const delresult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (delresult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete(
        `roles/${roleId}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('取消权限失败')
      }
      this.getRolesList()
      this.$message.success('取消权限成功')
    },
    // 分配权限
    async setRightRoles(role) {
      // 获取角色id等待提交参数
      this.roleId = role.id
      // 首先获得所有权限列表数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // 获取权限列表成功后要将数据渲染出来，选择了tree型数据
      this.setRightList = res.data
      this.getTreeNodeKeys(role, this.dfkeys)
      this.setRightDialogVisible = true
    },
    // 获取默认选好三级的权限id，赋值给树形控件
    getTreeNodeKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getTreeNodeKeys(item, arr)
      })
    },
    // 提交树形控件表单数据
    async setRight() {
      //角色授权参数中的勾选id
      const keys = [
        //...为扩展运算符，可以将一个数组转为用逗号（，）分隔的参数序列
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将数组id变为字符串id
      const idStr = keys.join(',')

      // 角色id&勾选id参数准备好了，开始提交参数
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      )
      if ((res.meta.status !== 200)) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 重置树形控件表单
    getRightDialogClosed() {
      this.dfkeys = []
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.Ycenter {
  display: flex;
  align-items: center;
}
</style>
